import java.util.concurrent.*;

/**
 * Reindeer class that is initially not at the north pole but comes back to
 * deliver presents for christmas.
 */
public class Reindeer extends Thread implements WinterHelper {

	// Latch to start all the threads
	private final CountDownLatch startSignal;
	// Name of the reindeer
	private final String name;
	// Barrier that confirms all the reindeer have arrived at the north pole
	private final static CyclicBarrier atWarmingHut = new CyclicBarrier(
			Properties.TOTAL_REINDEER);
	// Latch that sends all the reindeer to the sleigh
	private final static CountDownLatch goToSleigh = new CountDownLatch(1);

	/**
	 * Constructor for the Reindeer class.
	 * 
	 * @param name
	 *            Name of the reindeer
	 * @param latch
	 *            The latch to start the thread
	 */
	public Reindeer(String name, CountDownLatch latch) {
		this.name = name;
		this.startSignal = latch;
	}

	@Override
	public int compareTo(WinterHelper helper) {
		if (helper.getClass() == Reindeer.class) {
			return 0;
		} else {
			return -1;
		}
	}

	@Override
	/**
	 * Sleep for a long initial time and then waits for all the reindeer
	 * to return. The last reindeer then gets Santa ready to deliver the presents.
	 */
	public void run() {

		try {
			// Waits to start with the rest of the threads
			startSignal.await();
		} catch (InterruptedException e) {
		}

		try {

			Thread.sleep(Properties.randomNumber(
					Properties.REINDEER_MIN_VACATION,
					Properties.REINDEER_MAX_VACATION));
			System.out.println(name + " goes to the warming hut.");

			// Last reindeer to arrive
			if (atWarmingHut.await() == 0) {
				System.out.println(name
						+ " has arrived last and goes to wake Santa.");
				WinterHelperQueue.getHelperQueue().add(this);
			}

			// Waits for the last reindeer to wake up santa
			goToSleigh.await();
			System.out.println(name + " is harnessed to the Sleigh.");

			// Waits for everyone to be ready at the sleigh
			Sleigh.allReady.await();
			System.out.println(name + " goes to the tropics.");

		} catch (InterruptedException e) {
		} catch (BrokenBarrierException e) {
		}

	}

	@Override
	public String toString() {
		return name;
	}

	/**
	 * The last reindeer that gets santa wakes him up and then tells the rest of
	 * the reindeer to go to the sleigh.
	 */
	public void helpMe() {
		goToSleigh.countDown();
	}
}